
#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import <sys/utsname.h>
#import <objc/runtime.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
#import "AES128.h"
#import "NSData+AES.h"
#import "NSString+AESCrypt.h"
#import "NSData+AES.h"
#import "NSData+AES1.h"
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
       NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
       NSString *isFirstInstall = [UserDefaults objectForKey:@"isFirstInstall"];
       if (![isFirstInstall isEqualToString:@""]&&isFirstInstall!=NULL&&isFirstInstall!=nil) {//不是第一次安装app,没同意隐私协议
           NSLog(@"不是第一次安装app");
//               NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//               [userDefaults setObject:@"0" forKey:@"isFirstInstall"];
//               [userDefaults synchronize];
           [self didFinishLaunchingWithOptions];
       }else{
           //    [self didFinishLaunchingWithOptions];
       }
   
    return YES;
}

-(void)didFinishLaunchingWithOptions{

    [NSThread sleepForTimeInterval:0.8];
    [[IQKeyboardManager sharedManager] setToolbarDoneBarButtonItemText:@"完成"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"N" forKey:@"voiceRoomIsOn"];//是否在音视频中
    [userDefaults setObject:@"0" forKey:@"agoTimeStamp"];
    [userDefaults setObject:@"N" forKey:@"isCalling"];//是否接通音视频
    [userDefaults setObject:@"N" forKey:@"isApplicationWillTerminate"];//是否程序被杀死
    [userDefaults synchronize];
 
    [self loadLaunch2];
    
    
//    [self messagenotification];
//    if ([Config getToken]) {
//        NSDictionary *saveOpen_app_config = [Config getOpenAppConfig];
//        if (saveOpen_app_config!=nil) {
//            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//            [userDefaults setObject:@"Y" forKey:@"is_LoadConfig"];
//            [userDefaults synchronize];
//            
////            NSDictionary *saveSystemConfig = [Config getOpenAppConfig];
////            if (saveSystemConfig!=nil) {
////                int is_examine=[saveSystemConfig[@"is_examine"] intValue];
////                if (is_examine==0) {
////                    NSLog(@"环境--0");
////                    CPTabBarController *tab = [[CPTabBarController alloc] init];
////                    self.tab=tab;

////                }else{
//                    NSLog(@"环境--1");
//        //            CPTabBarController *tab = [[CPTabBarController alloc] init];
//        //            self.tab=tab;
//                    FLTabBarController *tab = [[FLTabBarController alloc] init];
//                    self.tab2=tab;
//                    self.window.rootViewController = tab;
////                }
////            }
//            

//        }
//    }
   
    /**启动IAP工具类*/
     [[IAPManager shared] startManager];
}

//-(UIWindow*)window{
//    if (!_window) {
//        UIWindow *window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//        self.window=window;
//        [self.window makeKeyAndVisible];
//    }
//    return _window;
//}
//app回到后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
//    NSInteger count = [[[NIMSDK sharedSDK] conversationManager] allUnreadCount];
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
    if (self.enterBackgroundHandler) {
        self.enterBackgroundHandler();
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopMatchingNSNotification" object:self userInfo:nil];//当在视频速配时，通知停止视频速配
    [[NSNotificationCenter defaultCenter] postNotificationName:@"searchStopNSNotification" object:self userInfo:nil];//停止搜索视频弹窗
}
//app回到前台
- (void)applicationWillEnterForeground:(UIApplication *)application{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"searchStartNSNotification" object:self userInfo:nil];//开始搜索视频弹窗
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"程序被杀死，applicationWillTerminate");
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"Y" forKey:@"isApplicationWillTerminate"];//是否程序被杀死
    [userDefaults synchronize];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillTerminateNotification" object:nil];
    
    /**结束IAP工具类*/
   [[IAPManager shared] stopManager];
}

-(void)messagenotification
{
//    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//        //ios8.0之后，注册远程推送
//
////        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound categories:nil]];
////        [[UIApplication sharedApplication] registerForRemoteNotifications];
//
//    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
//    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
//    #else
//        //ios8.0之前，注册远程推送
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|
//         UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound];
//        [[UIApplication sharedApplication] registerForRemoteNotifications];
//    #endif
    
    if (@available(iOS 11.0, *))
    {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!granted)
            {
//                dispatch_async_main_safe(^{
//                    [[UIApplication sharedApplication].keyWindow makeToast:@"请开启推送功能否则无法收到推送通知".ntes_localized duration:2.0 position:CSToastPositionCenter];
//                })
                NSLog(@"请开启推送功能否则无法收到推送通知");
            }
        }];
    }
    else
    {
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // 上传devicetoken至云信服务端。
//    [[NIMSDK sharedSDK] updateApnsToken:deviceToken];
}



-(void)loadLaunch2{
    
    NSString *path=@"/system/open_app_config";
    NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url path:path parameters:@{} success:^(NSURLResponse *operation, id successObject) {
        NSLog(@"%@",successObject);
        
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
          
        }
        
        
        NSDictionary *saveOpen_app_config=dic;
        [Config saveOpen_app_config:saveOpen_app_config];
        NSDictionary *saveOpen_app_config1 = [Config getOpenAppConfig];
        NSString *tim_app_id=@"";
        NSString *cos_bucket_name=@"";
        NSString *cos_region=@"";
         
        if (saveOpen_app_config1!=nil) {
            tim_app_id=saveOpen_app_config1[@"tim_app_id"];
            NSLog(@"tim_app_id=%@",tim_app_id);
            cos_bucket_name=saveOpen_app_config1[@"cos_bucket_name"];
            NSLog(@"cos_bucket_name=%@",cos_bucket_name);
            cos_region=saveOpen_app_config1[@"cos_region"];
            NSLog(@"cos_region=%@",cos_region);
        }
        
        //腾讯IM
        
      
        
//        if ([Config getToken]) {
//            
//            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//            NSString *is_LoadConfig=[userDefaults objectForKey:@"is_LoadConfig"];
//            if(![is_LoadConfig isEqualToString:@"Y"]){
//                [userDefaults setObject:@"Y" forKey:@"is_LoadConfig"];
//                [userDefaults synchronize];
//                
////                NSDictionary *saveSystemConfig = [Config getOpenAppConfig];
////                if (saveSystemConfig!=nil) {
////                    int is_examine=[saveSystemConfig[@"is_examine"] intValue];
////                    if (is_examine==0) {
////                        NSLog(@"环境--0");
////                        CPTabBarController *tab = [[CPTabBarController alloc] init];
////                        self.tab=tab;

////                    }else{
//                        NSLog(@"环境--1");
//            //            CPTabBarController *tab = [[CPTabBarController alloc] init];
//            //            self.tab=tab;
//                        FLTabBarController *tab = [[FLTabBarController alloc] init];
//                        self.tab2=tab;
//                        self.window.rootViewController = tab;
////                    }
////                }
//            }
//        }
        
        PUTabBarController *tab = [[PUTabBarController alloc] init];
        self.tab2=tab;
        self.window.rootViewController = tab;
        
        if([Config getID]){
            if ([Config getToken]) {
                [self userInfo];
            }
            [self loginYunXin];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSDictionary *saveOpen_app_config = [Config getOpenAppConfig];
            if (saveOpen_app_config==nil) {
                [self loadLaunch2];
            }else{
//                if ([Config getToken]) {
//                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//                    [userDefaults setObject:@"Y" forKey:@"is_LoadConfig"];
//                    [userDefaults synchronize];
//                    
////                    NSDictionary *saveSystemConfig = [Config getOpenAppConfig];
////                    if (saveSystemConfig!=nil) {
////                        int is_examine=[saveSystemConfig[@"is_examine"] intValue];
////                        if (is_examine==0) {
////                            NSLog(@"环境--0");
////                            CPTabBarController *tab = [[CPTabBarController alloc] init];
////                            self.tab=tab;

////                        }else{
//                            NSLog(@"环境--1");
//                //            CPTabBarController *tab = [[CPTabBarController alloc] init];
//                //            self.tab=tab;
//                            FLTabBarController *tab = [[FLTabBarController alloc] init];
//                            self.tab2=tab;
//                            self.window.rootViewController = tab;
////                        }
////                    }
//                }
                
                PUTabBarController *tab = [[PUTabBarController alloc] init];
                self.tab2=tab;
                self.window.rootViewController = tab;
            }
            
        });
    }];
}
- (void)onUserSigExpired{
    [self loadimSig];
}
-(void)loadimSig{
    NSDictionary *param =@{
                            
                           };
    NSString *path=@"/system/get_im_sig";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        
        NSString *result=successObject[@"result"];
        NSString *im_sig=@"";
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200) {
            im_sig=[NSString stringWithFormat:@"%@",dic[@"im_sig"]];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:im_sig forKey:@"im_sig"];
            [userDefaults synchronize];
            [self loginYunXin];
        } else {
//            [self showSVProgressHUDStr:successObject[@"message"]];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
    }];
}
-(void)addCPTabBarController{
    if ([Config getToken]) {
//        [self userInfo];
        [self loginYunXin];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        NSString *is_LoadConfig=[userDefaults objectForKey:@"is_LoadConfig"];
//        if(![is_LoadConfig isEqualToString:@"Y"]){
            [userDefaults setObject:@"Y" forKey:@"is_LoadConfig"];
            [userDefaults synchronize];
        
//            NSDictionary *saveSystemConfig = [Config getOpenAppConfig];
//            if (saveSystemConfig!=nil) {
//                int is_examine=[saveSystemConfig[@"is_examine"] intValue];
//                if (is_examine==0) {
//                    NSLog(@"环境--0");
//                    CPTabBarController *tab = [[CPTabBarController alloc] init];
//                    self.tab=tab;
//                    self.window.rootViewController = tab;
//                }else{
                    NSLog(@"环境--1");
        //            CPTabBarController *tab = [[CPTabBarController alloc] init];
        //            self.tab=tab;
                    PUTabBarController *tab = [[PUTabBarController alloc] init];
                    self.tab2=tab;
                    self.window.rootViewController = tab;
//                }
//            }
//        }
    }
}
-(void)loginYunXin
{
   
    if ([Config getToken]) {
        
        //44129000274
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *im_sig=[userDefaults objectForKey:@"im_sig"];
        
        NSString *userID = [NSString stringWithFormat:@"%@",[Config getID]];
        NSString *userSig = im_sig;
       
        
        NSDictionary *saveOpen_app_config1 = [Config getOpenAppConfig];
        NSString *tim_app_id=@"";
        if (saveOpen_app_config1!=nil) {
            tim_app_id=saveOpen_app_config1[@"tim_app_id"];
        }
//        [[TencentCloudCustomerManager sharedManager] loginWithSdkAppID:[tim_app_id intValue] userID:userID userSig:userSig completion:^(NSError *error) {
//             if (error.code == 0) {
//               // 如果没有修改默认的客服号 ID 就不需要调用该函数。可从智能客服管理端首页查看: https://desk.qcloud.com/﻿
//               // [[TencentCloudCustomerManager sharedManager] setCustomerServiceUserID: "@customer_service_account"];
//                 NSLog(@"在线客服登录成功");
//             } else {
//               NSLog(@"在线客服登录失败");
//             }
//        }];
    }
}
- (void)onTotalUnreadMessageCountChanged:(UInt64) totalUnreadCount {
    // 会话未读总数变化
    NSLog(@"会话未读总数变化");
    NSDictionary *resultDic=@{@"totalUnreadCount":[NSString stringWithFormat:@"%ld",(long)totalUnreadCount]};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chatingVCUnReadCount" object:self userInfo:resultDic];
}
-(void)userInfo{
    
    NSDictionary *param =@{
                        
                          };
    NSString *path=@"/user/info";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200||[successObject[@"code"] integerValue] == 0) {
            LiveUser *userInfo = [[LiveUser alloc] initWithDic:dic];
            userInfo.token=[Config getToken];
            [Config saveProfile:userInfo];
            
        } else {
            [self showSVProgressHUDStr:successObject[@"message"]];
//            if (self.tab!=nil) {
//                [self.tab presentLoginViewController];
//            }
//            if (self.tab2!=nil) {
                [self.tab2 presentLoginViewController];
//            }
           
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
    }];
    
}

-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}

//MD5加密
- (NSString *) md5:(NSString *) input {
    if (input==nil) {
        input=@"";
    }
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr,(CC_LONG)strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}

@end
